package com.padgett.resourcemanagement.client;

import java.io.IOException;
import java.util.Date;
import java.util.logging.Logger;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.Text;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.appengine.labs.repackaged.org.json.JSONException;
import com.google.appengine.labs.repackaged.org.json.JSONObject;
import com.padgett.resourcemanagement.data.ClientDAO;

/**
 * Save client.
 * 
 * @author andyleung
 * 
 */
@SuppressWarnings("serial")
public class SaveBusinessClientServlet extends HttpServlet{
	private static final Logger logger=Logger.getLogger(SaveBusinessClientServlet.class.getName());
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		String id=req.getParameter("clientId");
		String clientNumber=req.getParameter("ClientNumber");
		String name=req.getParameter("Name");
		String businessName=req.getParameter("BusinessName");
		String expiryDateString=req.getParameter("ExpiryDate");
		String registeredAddress=req.getParameter("RegisteredAddress");
		String businessAddress=req.getParameter("BusinessAddress");
		String mailingAddress=req.getParameter("MailingAddress");
		String contactPerson=req.getParameter("ContactPerson");
		String homePhone=req.getParameter("HomePhone");
		String cellPhone=req.getParameter("CellPhone");
		String businessPhone=req.getParameter("BusinessPhone");
		String fax=req.getParameter("Fax");
		String email=req.getParameter("Email");
		String natureOfBusiness=req.getParameter("NatureOfBusiness");
		String fiscalYearEndString=req.getParameter("FiscalYearEnd");
		String status=req.getParameter("Status");
		String article=req.getParameter("Article");
		String form1=req.getParameter("Form1");
		String HST=req.getParameter("HST");
		String payroll=req.getParameter("Payroll");
		String tax=req.getParameter("Tax");
		String importExport=req.getParameter("ImportExport");
		String businessNumber=req.getParameter("BusinessNumber");
		String BusinessNumberConsentForm=req.getParameter("BusinessNumberConsentForm");
		String WSIBNumber=req.getParameter("WSIBNumber");
		String WSIBNumberConsentForm=req.getParameter("WSIBNumberConsentForm");
		String EHTNumber=req.getParameter("EHTNumber");
		String EHTNumberConsentForm=req.getParameter("EHTNumberConsentForm");
		String accountant=req.getParameter("Accountant");
		String PASID=req.getParameter("PASID");
		String typeOfServices=req.getParameter("TypeOfServices");
		String pickupDateString=req.getParameter("PickupDate");
		String note=req.getParameter("Note");
		// Client Number and Legal Number must be presented to generate a unique key
		UserService userService=UserServiceFactory.getUserService();
		User user=userService.getCurrentUser();
		Key key=null;
		Entity client=null;
		if(id==null||id.isEmpty()){
			key=new KeyFactory.Builder("Client", user.getUserId())
			.addChild("Client", "Business")
			.addChild("Client", clientNumber)
			.getKey();
			client=new Entity(key);
			client.setProperty("CreatedBy", user.getNickname());
			client.setProperty("CreatedDate", new Date(System.currentTimeMillis()));
			client.setProperty("LastModifiedBy", user.getNickname());
			client.setProperty("LastModifiedDate", new Date(System.currentTimeMillis()));
		}else{
			key=KeyFactory.stringToKey(id);
			client=ClientDAO.loadEntity(key);
			client.setProperty("LastModifiedBy", user.getNickname());
			client.setProperty("LastModifiedDate", new Date(System.currentTimeMillis()));
		}
		client.setProperty("ClientNumber", clientNumber);
		client.setProperty("Name", name);
		client.setProperty("BusinessName", businessName);
		client.setProperty("Type", "Business");
		client.setUnindexedProperty("RegisteredAddress", registeredAddress);
		client.setUnindexedProperty("BusinessAddress", businessAddress);
		client.setUnindexedProperty("MailingAddress", mailingAddress);
		client.setUnindexedProperty("ContactPerson", contactPerson);
		client.setUnindexedProperty("BusinessPhone", businessPhone);
		client.setUnindexedProperty("CellPhone", cellPhone);
		client.setUnindexedProperty("HomePhone", homePhone);
		client.setUnindexedProperty("Fax", fax);
		client.setUnindexedProperty("Email", email);
		client.setUnindexedProperty("NatureOfBusiness", natureOfBusiness);
		client.setUnindexedProperty("Status", status);
		client.setUnindexedProperty("Article", article);
		client.setUnindexedProperty("Form1", form1);
		client.setUnindexedProperty("HST", HST);
		client.setUnindexedProperty("Payroll", payroll);
		client.setUnindexedProperty("Tax", tax);
		client.setUnindexedProperty("ImportExport", importExport);
		client.setUnindexedProperty("BusinessNumber", businessNumber);
		client.setUnindexedProperty("BusinessNumberConsentForm", BusinessNumberConsentForm);
		client.setUnindexedProperty("WSIBNumber", WSIBNumber);
		client.setUnindexedProperty("WSIBNumberConsentForm", WSIBNumberConsentForm);
		client.setUnindexedProperty("EHTNumber", EHTNumber);
		client.setUnindexedProperty("EHTNumberConsentForm", EHTNumberConsentForm);
		client.setProperty("Accountant", accountant);
		client.setProperty("PASID", PASID);
		client.setProperty("TypeOfServices", typeOfServices);
		if(pickupDateString!=null&&!pickupDateString.isEmpty()){
			int pickupDate=Integer.parseInt(pickupDateString);
			client.setUnindexedProperty("PickupDate", pickupDate);
		}
		Date expiryDate=null;
		if(expiryDateString!=null&&!expiryDateString.isEmpty()){
			expiryDate=new Date(Long.parseLong(expiryDateString));
			client.setUnindexedProperty("ExpiryDate", expiryDate);
		}
		Date fiscalYearEnd=null;
		if(fiscalYearEndString!=null&&!fiscalYearEndString.isEmpty()){
			fiscalYearEnd = new Date(Long.parseLong(fiscalYearEndString));
			client.setUnindexedProperty("FiscalYearEnd", fiscalYearEnd);
		}
		if(note!=null){
			client.setUnindexedProperty("Note", new Text(note));
		}
		Key savedKey=ClientDAO.saveEntity(client);
		JSONObject response=new JSONObject();
		try {
			if(savedKey!=null){
				response.put("success", "true");
				response.put("clientId", KeyFactory.keyToString(savedKey));
			}else{
				response.put("success", "false");
				response.put("error", "Unable to save client at the moment.");
			}
		} catch (JSONException e) {
			logger.severe(e.getMessage());
		}
		resp.getWriter().write(response.toString());
	}

}
